#!/bin/bash

set -euo pipefail

if [[ $(id -u) -ne 0 ]]; then
  echo "请以 root 用户运行该脚本。" >&2
  exit 1
fi

if ! command -v yum >/dev/null 2>&1; then
  echo "未找到 yum，请确认系统环境是否为基于 RPM 的发行版。" >&2
  exit 1
fi

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)

RPM_PYTHON_MELD3="python-meld3-0.6.10-1.el7.x86_64.rpm"
RPM_SUPERVISOR="supervisor-3.4.0-1.el7.noarch.rpm"
RPM_FILES=("$RPM_PYTHON_MELD3" "$RPM_SUPERVISOR")

echo ">>> 校验离线 RPM 包是否存在于 ${SCRIPT_DIR}"
for rpm in "${RPM_FILES[@]}"; do
  if [[ ! -f "${SCRIPT_DIR}/${rpm}" ]]; then
    echo "缺少 ${rpm}，请确认已将 RPM 包上传到脚本目录。" >&2
    exit 1
  fi
done

if rpm -q supervisor >/dev/null 2>&1; then
  echo ">>> 检测到系统已安装 supervisor，跳过 RPM 安装步骤。"
else
  echo ">>> 使用本地 YUM 源安装 python3"
  yum -y install python3

  echo ">>> 安装 python-meld3"
  yum -y localinstall "${SCRIPT_DIR}/${RPM_PYTHON_MELD3}"

  echo ">>> 安装 supervisor"
  yum -y localinstall "${SCRIPT_DIR}/${RPM_SUPERVISOR}"
fi

SUP_BASE="/opt/supervisor"
SUP_CONF="${SUP_BASE}/supervisord.conf"
SUP_CONF_DIR="${SUP_BASE}/conf.d"
SUP_LOG_DIR="${SUP_BASE}/logs"
SUP_RUN_DIR="${SUP_BASE}/run"

echo ">>> 初始化 Supervisor 目录结构"
mkdir -p "${SUP_CONF_DIR}" "${SUP_LOG_DIR}" "${SUP_RUN_DIR}"

if [[ -f "${SUP_CONF}" ]]; then
  echo "检测到已存在的 ${SUP_CONF}，备份为 ${SUP_CONF}.bak"
  cp -a "${SUP_CONF}" "${SUP_CONF}.bak"
fi

echo ">>> 生成默认 supervisord.conf"
cat >"${SUP_CONF}" <<'EOF'
[unix_http_server]
file = /opt/supervisor/run/supervisor.sock
chmod = 0700

[inet_http_server]
port = 0.0.0.0:9001
username = admin
password = hmgsoft



[supervisord]
logfile = /opt/supervisor/logs/supervisord.log
logfile_maxbytes = 50MB
logfile_backups = 10
pidfile = /opt/supervisor/run/supervisord.pid
childlogdir = /opt/supervisor/logs
loglevel = info
nodaemon = false
minfds = 1024
minprocs = 200

[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl = unix:///opt/supervisor/run/supervisor.sock

[include]
files = /opt/supervisor/conf.d/*.ini
EOF

echo ">>> 更新 /etc/supervisord.conf 指向 /opt/supervisor/supervisord.conf"
if [[ -f /etc/supervisord.conf && ! -L /etc/supervisord.conf ]]; then
  cp -a /etc/supervisord.conf /etc/supervisord.conf.bak.$(date +%Y%m%d%H%M%S)
fi
ln -sfn "${SUP_CONF}" /etc/supervisord.conf

echo ">>> 重载 systemd 配置并启用 supervisord 服务"
systemctl daemon-reload || true
systemctl enable supervisord
systemctl restart supervisord

HTTP_PORT="9001"

echo ">>> 配置 firewalld 放行 ${HTTP_PORT}/tcp (若 firewalld 已启用)"
if systemctl is-active --quiet firewalld; then
  if ! firewall-cmd --list-ports | grep -qw "${HTTP_PORT}/tcp"; then
    firewall-cmd --permanent --add-port=${HTTP_PORT}/tcp
    firewall-cmd --reload
  else
    echo "端口 ${HTTP_PORT}/tcp 已在 firewalld 中放行，跳过。"
  fi
else
  echo "firewalld 未运行，跳过端口放行步骤。"
fi

echo ">>> 安装完成，可通过 supervisorctl status 查看受管进程状态。"
